package com.predic8.membrane.servlet;

import com.predic8.membrane.core.Constants;
import com.predic8.membrane.core.Router;
import com.predic8.membrane.core.config.spring.LocationXmlWebApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MembraceRouteServletContextListener implements ServletContextListener {
    private static Logger logger =  LoggerFactory.getLogger(MembraceRouteServletContextListener.class);

    private XmlWebApplicationContext appCtx;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
//        ServletContextListener.super.contextInitialized(sce);
        try{
            logger.info(Constants.PRODUCT_NAME + " starting...");

            logger.debug("loading proxies configuration from: " + getProxiesXmlLocation(sce));

            // 加载config xml file
            appCtx = new LocationXmlWebApplicationContext();
            Router router = RouteHelper.initializeRoutersFromSpringWebContext(appCtx, sce.getServletContext(), getProxiesXmlLocation(sce));
            if (router != null)
                throw new RuntimeException("A <router> with a <servletTransport> cannot be used with MembraneServletContextListener. Use MembraneServlet instead.");

            logger.info(Constants.PRODUCT_NAME + " running.");

        }catch (Exception e){
            logger.error(e.getMessage());
            throw new RuntimeException("Router not started!", e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
//        ServletContextListener.super.contextDestroyed(sce);
        try{
            appCtx.stop();
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    private String getProxiesXmlLocation(ServletContextEvent sce) {
        return sce.getServletContext().getInitParameter("proxiesXml");
    }
}
